#Region " Imports "

Imports System.Data
Imports BlazeApps.Library.Menus
Imports BlazeApps.Library.TreeViews

#End Region

Partial Class Usercontrols_Options_MenuBuilder
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Private DataPageLocal As New PagedDataSource

    Protected Property PageGuid() As Guid
        Get
            Return GetGuidFromVS("PageGuid")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("PageGuid", value)
        End Set
    End Property

    Protected Property NodeID() As Integer
        Get
            Return GetIntegerFromVS("NodeID")
        End Get
        Set(ByVal value As Integer)
            ViewState.Add("NodeID", value)
        End Set
    End Property

    Public Property PageTitle() As String
        Get
            Return GetStringFromVS("PageTitle")
        End Get
        Set(ByVal value As String)
            ViewState.Add("PageTitle", value)
        End Set
    End Property

    Public Property sortCriteria() As String
        Get
            Return CStr(ViewState("sortCriteria"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortCriteria") = Value
        End Set
    End Property

    Public Property sortDir() As String
        Get
            Return CStr(ViewState("sortDir"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortDir") = Value
        End Set
    End Property

    Public Property DataLoaded() As Boolean
        Get
            Return GetBooleanFromVS("DataLoaded")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("DataLoaded", value)
        End Set
    End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.MessageLabel = Me.uxMessagesLabel
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SetPageTitle("Menu Builder")

        GetQueryStringValues()

        If IsUserAuthenticated = True And ShowControls(SecurityMask.Editor, True) Then
            If Me.Page.IsPostBack = False Then
                PopulateRootLevel(Me.uxMenuTreeView, TreeViewNodes.TreeType.MenuTree, CurrentUserID)

                Me.sortCriteria = "title"
                Me.sortDir = "asc"

                LoadPage()
            End If

            ConfigBaseNavCtrls()

            If Me.Page.IsPostBack = False Then
                BindDataItems()
            End If
        End If

        Me.uxTitleTextbox.Text = PageTitle

        Me.uxEditorPanel.Visible = ShowControls(SecurityMask.Editor, True)

        If PageGuid = Guid.Empty Then
            Me.uxUrlPanel.Visible = True
            Me.uxUrlPanel.Enabled = True
        End If

    End Sub

#End Region

#Region " Save Data "

	Private Function SaveRolesForMenu() As String

		Dim Roles As New StringBuilder

		For Each li As ListItem In Me.uxRolesCheckBoxList.Items
			If li.Selected Then
				Roles.Append(String.Format("{0}, ", li.Text.Trim))
			End If
		Next

		If Roles.Length > 0 Then
			If Right(Roles.ToString, 2) = ", " Then
				Roles.Length = Roles.Length - 2
			End If
		End If

		Return Roles.ToString.Trim

	End Function

#End Region

#Region " Load Data "

    Private Sub LoadPage()
		LoadPageSize(Me.uxPageSizeDropDownList)
		LoadRolesList(Me.uxRolesCheckBoxList)
	End Sub

	Private Sub LoadTree()
		Me.uxMenuTreeView.Nodes.Clear()
		PopulateRootLevel(Me.uxMenuTreeView, TreeViewNodes.TreeType.MenuTree, CurrentUserID)
		Me.uxMenuTreeView.ExpandAll()
	End Sub

	Private Sub LoadRolesForMenu(ByVal MenuItem As MenuTreeNodeDetail)
		Dim Roles As String()
		Dim iI As Integer

		'Clear the list each time a node is selected
		For Each li As ListItem In Me.uxRolesCheckBoxList.Items
			If li.Selected Then
				li.Selected = False
			End If
		Next

		Roles = Split(MenuItem.Roles, ",")

		'Reload select items based on the currently node
		If Roles.Length > 0 Then

			For iI = 0 To Roles.Length - 1

				Dim CB As ListItem = Me.uxRolesCheckBoxList.Items.FindByText(Roles.GetValue(iI).ToString.Trim)
				If CB IsNot Nothing Then
					CB.Selected = True
				End If

			Next

		End If

	End Sub

	Private Sub GetNode()
		Dim MenuItem As MenuTreeNodeDetail = MenuTreeNodeDetail.GetMenuTreeNodeDetail(NodeID)

		If PageGuid = Guid.Empty Then
			Me.uxTitleTextbox.Text = MenuItem.Title
			Me.uxDescriptionTextbox.Text = MenuItem.Description
			Me.uxURLTextbox.Text = MenuItem.Url
		End If

		If MenuItem.ParentChildCount = 0 Then
			Me.uxDeleteButton.Enabled = True
		Else
			Me.uxDeleteButton.Enabled = False
		End If

		LoadRolesForMenu(MenuItem)

	End Sub

	Public Overloads Overrides Sub BindDataItems()

		Dim List As New MenuList
		Dim DT As New DataTable
		Dim DV As New DataView

		DT = List.GetMenuList().Tables(0)

		Me.RecordCount = DT.Rows.Count

		DV.Table = DT

		DV.Sort = Me.sortCriteria & " " & Me.sortDir

		Me.DataPage.DataSource = DV
		Me.DataPage.AllowPaging = True
		Me.DataPage.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
		Me.DataPage.CurrentPageIndex = Me.PageNumber

		CreatePagingLinks()

		DataLoaded = True

		With Me.uxResultsGridView
			.DataSource = Me.DataPage
			.DataBind()
		End With

		DataLoaded = False

	End Sub

#End Region

#Region " Form Controls Events "

	Protected Sub uxMenuTreeView_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxMenuTreeView.SelectedNodeChanged
		NodeID = Convert.ToInt32(Me.uxMenuTreeView.SelectedValue)

		GetNode()
		BindDataItems()

	End Sub

	Protected Sub uxMenuTreeView_TreeNodePopulate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles uxMenuTreeView.TreeNodePopulate
		PopulateSubLevel(e.Node.Value.Trim, e.Node, TreeViewNodes.TreeType.MenuTree, CurrentUserID)
	End Sub

	Protected Sub uxSaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxSaveButton.Click
		Dim MenuItem As MenuTreeNodeDetail = MenuTreeNodeDetail.NewMenuTreeNodeDetail()

		MenuItem.Title = Me.uxTitleTextbox.Text.ToString.Trim
		MenuItem.Url = CreateValidURL()
		MenuItem.Description = Me.uxDescriptionTextbox.Text.ToString.Trim
		MenuItem.Roles = SaveRolesForMenu()

		If Me.uxMenuTreeView.SelectedValue = String.Empty Then
			MenuItem.Parent = 1
		Else
			MenuItem.Parent = Convert.ToInt32(Me.uxMenuTreeView.SelectedValue)
		End If

		MenuItem.Save()

		LoadTree()

		BindDataItems()

	End Sub

	Protected Sub uxUpdateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxUpdateButton.Click
		Dim MenuItem As MenuTreeNodeDetail = MenuTreeNodeDetail.GetMenuTreeNodeDetail(Convert.ToInt32(Me.uxMenuTreeView.SelectedValue))

		MenuItem.Id = Convert.ToInt32(Me.uxMenuTreeView.SelectedValue)
		MenuItem.Title = Me.uxTitleTextbox.Text.ToString.Trim
		MenuItem.Url = CreateValidURL()
		MenuItem.Description = Me.uxDescriptionTextbox.Text.ToString.Trim
		MenuItem.Parent = MenuItem.Parent
		MenuItem.Roles = SaveRolesForMenu()

		MenuItem.Save()

		LoadTree()
		BindDataItems()

	End Sub

	Protected Sub uxDeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxDeleteButton.Click

		If Convert.ToInt32(Me.uxMenuTreeView.SelectedValue) <> 1 Then
			MenuTreeNodeDetail.DeleteMenuTreeNodeDetail(Convert.ToInt32(Me.uxMenuTreeView.SelectedValue))
		End If

		LoadTree()
		BindDataItems()

	End Sub

	Protected Sub DeleteNode(ByVal sender As Object, ByVal e As CommandEventArgs)
		If Convert.ToInt32(e.CommandArgument.ToString) <> 1 Then
			MenuTreeNodeDetail.DeleteMenuTreeNodeDetail(Convert.ToInt32(e.CommandArgument.ToString))
		End If

		LoadTree()
		BindDataItems()
	End Sub

	Protected Sub EditNode(ByVal sender As Object, ByVal e As CommandEventArgs)

		Dim Values As String()
		Dim ParentCount As Integer

		Values = Split(e.CommandArgument.ToString, "|")

		NodeID = Convert.ToInt32(Values(0))
		ParentCount = CType(Values(1), Integer)

		If ParentCount = 0 Then
			Me.uxDeleteButton.Enabled = True
		Else
			Me.uxDeleteButton.Enabled = False
		End If

		GetNode()
	End Sub

	Protected Sub uxResultsGridView_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles uxResultsGridView.RowCreated
		Dim LB As LinkButton = CType(e.Row.FindControl("uxDeleteNodeLinkButton"), LinkButton)

		If DataLoaded = True Then
			If e.Row.RowType = DataControlRowType.DataRow Then

				If e.Row.DataItem("parentchildcount") = 0 Then
					LB.Enabled = True
				Else
					LB.Enabled = False
				End If

			End If
		End If
    End Sub

    Protected Sub uxResultsGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles uxResultsGridView.Sorting
        'Get the Sort by Value from the Sortexpression field on the column
        If Me.sortCriteria = e.SortExpression Then
            If Me.sortDir = "desc" Then
                Me.sortDir = "asc"
            Else
                Me.sortDir = "desc"
            End If
        End If

        ' Assign the column clicked to the sortCriteria property
        Me.sortCriteria = e.SortExpression

        'Calls the function to rebuild the datagrid view, with the new sort order
        BindDataItems()
    End Sub

#End Region

#Region " Helpers and Methods "

	Protected Sub GetQueryStringValues()
		PageGuid = GetGuidFromQueryString("id")
	End Sub

	Private Sub ConfigBaseNavCtrls()

		Me.PagingTopPanel = Me.uxPagingTopPanel
		Me.PagingBottomPanel = Me.uxPagingBottomPanel

		Me.RepeaterTop = Me.uxPagesTopRepeater
		Me.RepeaterBottom = Me.uxPagesBottomRepeater

		Me.NextTopLinkButton = Me.uxTopNextLinkButton
		Me.PreviousTopLinkButton = Me.uxTopPrevLinkButton
		Me.NextBottomLinkButton = Me.uxBottomNextLinkButton
		Me.PreviousBottomLinkButton = Me.uxBottomPrevLinkButton

		Me.DataPage = DataPageLocal
		Me.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
		Me.PagesToDisplay = 10

		Me.ItemsPerPageDropDown = Me.uxPageSizeDropDownList
		Me.ItemsPerPageLabel = Me.uxItemsPerPageLabel
		Me.PagerInfoLabel = Me.uxPagerInfoLabel

		AddHandler Me.RepeaterTop.ItemCommand, AddressOf PagingRepeater_ItemCommand
		AddHandler Me.RepeaterBottom.ItemCommand, AddressOf PagingRepeater_ItemCommand

	End Sub

	Private Function CreateValidURL() As String
		If PageGuid = Guid.Empty Then

			If InStr(Me.uxURLTextbox.Text.ToString.Trim, Request.ServerVariables("HTTP_HOST")) > 0 Then
				If InStr(Me.uxURLTextbox.Text.ToString.Trim, "?") = 0 Then
					Return String.Format("~/{0}?mid={1}", Me.uxURLTextbox.Text.Substring(InStrRev(Me.uxURLTextbox.Text.ToString.Trim, "/")), Guid.NewGuid)
				Else
					Return String.Format("~/{0}&mid={1}", Me.uxURLTextbox.Text.Substring(InStrRev(Me.uxURLTextbox.Text.ToString.Trim, "/")), Guid.NewGuid)
				End If
			Else
				If InStr(Me.uxURLTextbox.Text.ToString.Trim, "~/") = 0 Then
					If InStr(Me.uxURLTextbox.Text.ToString.Trim, "?") = 0 Then
						Return String.Format("~/{0}?mid={1}", Me.uxURLTextbox.Text.ToString.Trim, Guid.NewGuid)
					Else
						Return String.Format("~/{0}&mid={1}", Me.uxURLTextbox.Text.ToString.Trim, Guid.NewGuid)
					End If
				Else
					If InStr(Me.uxURLTextbox.Text.ToString.Trim, "?") = 0 Then
						Return String.Format("{0}?mid={1}", Me.uxURLTextbox.Text.ToString.Trim, Guid.NewGuid)
					Else
						Return String.Format("{0}&mid={1}", Me.uxURLTextbox.Text.ToString.Trim, Guid.NewGuid)
					End If
				End If
			End If
		Else
			Return String.Format("~/default.aspx?pid=viewer&id={0}&mid={1}", PageGuid, Guid.NewGuid)
		End If
	End Function

#End Region

End Class
